<template>
  <!-- <div > -->
  <div class="dag-box" style="display: flex">
    <div class="dag-nav">
      <a href="javascript:;" class="go-back" @click="$router.go(-1)"></a>
      <ul class="dag-nav-box">
        <li
          :class="['dag-nav-item nav-menu-icon1', { active: dagActive == 1 }]"
          @click="dagActive = 1"
        >
          画布
        </li>
        <li
          :class="['dag-nav-item nav-menu-icon1', { active: dagActive == 2 }]"
          @click="dagActive = 2"
        >
          文件
        </li>
        <!-- <li :class="['dag-nav-item nav-menu-icon1', {'active': dagActive == 3}]" @click="dagActive = 3">数据集</li> -->
        <!-- <li :class="['dag-nav-item nav-menu-icon1', {'active': dagActive == 4}]" @click="dagActive = 4">监控</li> -->
        <!-- <li :class="[
            'dag-nav-item',
            e.meta.icon,
            { 'active': e.name == $route.name },
          ]" @click="skip(e)" v-for="(e, i) in nav" :key="i">
          {{ e.meta.title }}
        </li> -->
      </ul>
    </div>
    <div class="wrap">
      <aside id="dag-stencil" class="panel-left">
        <div v-if="dagActive == 1">
          <StencilTree
            v-if="enabled"
            :taskName="canvasDetail.data && canvasDetail.data.name"
          ></StencilTree>
        </div>
        <dag-file v-if="dagActive == 2" />
        <dag-dataset v-if="dagActive == 3" :canvasData="canvasDetail.data" />
        <dag-log v-if="dagActive == 4" />
      </aside>
      <main class="panel-center">
        <div class="tool-bar">
          <ToolBar
            v-if="enabled"
            :current-select="currentSelect"
            @saveStrategy="handleSaveDag"
            @runAll="runAll"
            @call-father="fatherMethodHandle"
            @childBySrc="childBySrc"
          >
          </ToolBar>
        </div>
        <div class="x6-graph-box">
          <div id="x6-graph-container" class="x6-graph-container"></div>
        </div>

        <div
          class="bottom-result"
          v-show="showBottomResult"
          v-loading="imgLoading"
          element-loading-text="运行中"
        >
          <a
            href="javascript:;"
            class="handle-btn"
            @click="showBottomResult = !showBottomResult"
          ></a>

          <el-table
            :height="
              this.resultData.table.length * 24 > 300
                ? '300'
                : `${this.resultData.table.length * 24}`
            "
            v-if="resultData.table && resultData.table.length"
            :data="resultData.table"
            style="width: 100%"
          >
            <el-table-column
              :prop="e"
              v-for="(e, i) in resultData.tableHead"
              :key="i"
              :label="`${e != 'index' ? e : '序号'}`"
            >
              <template slot-scope="scope">
                {{ scope.row[`${e}`] }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </main>
      <aside class="panel-right">
        <!-- <header class="base-header-title">属性编辑</header> -->
        <div v-if="enabled" class="right-content">
          <EditConditionForm
            ref="conditionForm"
            v-if="currentSelect != 'none'"
            :form-data="cellData"
            @updateCellData="setNodeInfo"
          ></EditConditionForm>
          <div v-show="currentSelect == 'none'" class="tips-info">
            <i class="el-icon-info"></i>请点击节点进行编辑
          </div>
        </div>
      </aside>
      <ContextMenu v-if="enabled"></ContextMenu>
    </div>
    <iframe
      v-if="ifJupiter"
      id="inlineFrameExample"
      title="Inline Frame Example"
      width="100%"
      :src="url"
    >
    </iframe>
  </div>

  <!-- </div> -->
</template>

<script>
// read_data 0 读取你的数据
// write_data 9 写入你的数据
// view_data 1 了解你的数据
// data_pre_handle 2 数据预处理
// machine_learning_model 3 机器学习模型
// evaluate_model 4 评估你的模型
// visualize 5 数据可视化
// feature_engineering 6 特征工程
// analyse_data 7 统计分析
// text_analysis 8 文本分析
// customize 100 自定义脚本

// 1 text 输入域
// 2 select 下拉选
// 3 number 整数数字
// 4 checkbox 单个复选框
// 5 path 选择文件
// 6 array 特殊的文本域，用来选择特征列，比如特征工程->特征变换
// 7 code 代码编辑器
// 8 database 选择数据源
import DagGraph from "@/views/dag/dagEdit/graph";
// import { commonEdage, commonPortsGroups } from "./const/config";
import ToolBar from "./components/ToolBar";
import ContextMenu from "./components/ContextMenu";
import EditConditionForm from "./components/EditConditionForm";
// import EditOrderForm from "./components/EditOrderForm";
import StencilTree from "./components/StencilTree";
// import { bus } from "@/main"
import { getCanvasDetail } from "@/api/dag";
import DagFile from "./components/dag-file";
import DagDataset from "./components/dag-dataset";
import DagLog from "./components/dag-log";
import { mapState, mapActions } from "vuex";
import { domain } from "@/config";

import {
  initCanvas,
  // kernelCanvas,
  notebookContent,
  // saveContentCanvas,
  sessionCanvas,
  kernelSpecCanvas,
  delSessionCanvas,
  sessionsLis,
  canvasAll,
  canvasRunAll,
} from "@/api/dag";

// import { DagData } from "./const/data.js";
let graph = null;
export default {
  name: "EditorDag",
  components: {
    StencilTree,
    ToolBar,
    ContextMenu,
    EditConditionForm,
    DagFile,
    DagDataset,
    DagLog,
    // EditOrderForm
  },
  data() {
    return {
      enabled: false,
      activeName: "nodeData",
      currentSelect: "none", // none、edge、pipeline、fork
      currentCell: null,
      cellData: {},
      graphData: null,
      canvasDetail: {},
      dagActive: 1,
      showBottomResult: false,
      resultData: {
        table: [],
        tableHead: [],
        imgData: "",
        scatter: null,
      },
      imgLoading: false,
      ifJupiter: false,
      url: "http://192.168.8.209:32658/notebook/x8gq9lw8/lab?",
    };
  },
  computed: mapState({
    dagStructure: (state) => state.dag.dagStructure,
  }),
  created() {},
  mounted() {
    this.initDagGraph();
    this.$EventBus.$on("resSteram", (e) => {
      this.handleRes(e);
    });
    async function asdasd() {
      let argumentData = sessionStorage.getItem("argumentData");
      await initCanvas(JSON.parse(argumentData));
    }
    window.asdasd = asdasd;
  },
  beforeDestroy() {
    DagGraph.destroy();
  },
  methods: {
    ...mapActions(["saveCanvas", "handleStructure"]),

    fatherMethodHandle() {
      this.ifJupiter = true;
    },
    childBySrc(childBySrc) {
      // console.log('childBySrc1111111',childBySrc);
      this.url = childBySrc;
      console.log("this.url", this.url);
    },
    fatherMethod() {
      // console.log('父组件方法');
      this.ifJupiter = false;
      console.log("23456789");
    },

    async runAll() {
      let argumentData = JSON.parse(sessionStorage.getItem("argumentData"));

      let res = await canvasRunAll({
        ...argumentData,
        sessionId: sessionStorage.getItem("sessionsId"),
      });

      this.handleStructure({ thisData: res.data });

      if (res.data) {
        this.handleRes(res.data);
      }
    },

    // 初始化x6图编辑引擎
    async initDagGraph() {
      graph = DagGraph.init("#x6-graph-container");
      this.enabled = true;
      this.initClickEvent();
      // // 装载流程图数据

      // DagData = {cells: []}
      let detail = await getCanvasDetail({ id: this.$route.query.canvas_id });
      this.canvasDetail = detail;
      if (!detail.data.url_prefix && detail.data.status == "running") {
        this.$message.error("任务未启动");
        this.$router.push({
          path: "/dag",
          query: { ...this.$route.query },
        });
        return;
      }
      console.log(detail.data);
      let argumentData = {
        jupyter_server_url: `http:${domain.split(":")[1]}:8081`,
        url_prefix: detail.data.url_prefix,
      };
      sessionStorage.setItem("argumentData", JSON.stringify(argumentData));
      await initCanvas(argumentData);
      let sessions = await sessionsLis(argumentData);
      let sessionsId = "",
        kernel = {};
      if (sessions.data.length == 0) {
        let resSession = await sessionCanvas(argumentData);
        sessionsId = resSession.data.id;
        kernel = resSession.data.kernel;
      } else {
        sessionsId = sessions.data[0].id;
        kernel = sessions.data[0].kernel;
        for (let i = 1; i < sessions.data.length; i++) {
          await delSessionCanvas({
            sessionId: sessions.data[i],
          });
        }
      }
      let nContent = await notebookContent(argumentData);
      if (
        !nContent.data ||
        !nContent.data.content ||
        !nContent.data.content.metadata
      ) {
        await kernelSpecCanvas(argumentData);
      }
      sessionStorage.setItem("sessionsId", sessionsId);
      sessionStorage.setItem("kernel", kernel);
      let canvasAllData = await canvasAll({
        id: this.$route.query.canvas_id,
      });
      sessionStorage.setItem("canvasAllData", JSON.stringify(canvasAllData));
      if (
        !canvasAllData.data ||
        !canvasAllData.data.canvas_cells ||
        !canvasAllData.data.canvas_cells.cells
      )
        return;
      let cells = JSON.parse(canvasAllData.data.canvas_cells.cells);
      cells.forEach((e) => {
        if (e.shape != "edge") {
          nContent.data.content.cells.forEach((ele) => {
            if (ele.metadata.component_id == e.id) {
              e.execution_count = ele.execution_count;
            }
          });
        }
      });
      if (!canvasAllData.data.canvas_cells) return;
      let DagData = { cells };
      // bus.$on('classifyDone', () => {
      //   console.log(2)
      //   DagGraph.initGraphShape(DagData);
      //   bus.$emit('graph', graph)
      //   console.log(graph)
      // })

      DagGraph.initGraphShape(DagData);
    },
    handleRes(e) {
      if (e.error && e.error.ename) {
        this.$message.error(
          `${e.error.ename}: ${e.error.evalue} ===> ${e.error.traceback[0]}`
        );
      }
      if (e.display && e.display.data) {
        this.handleDisplay(e.display.data);
        return;
      } else {
        this.resultData.imgData = "";
      }
      if (e.stream && e.stream[0]) {
        this.handleSteram(e.stream);
        return;
      } else {
        this.resultData.table = [];
        this.resultData.tableHead = [];
      }
    },
    handleDisplay(data) {
      this.resultData = {
        imgData: `data:image/png;base64,${data["image/png"]}`,
      };
      this.showBottomResult = true;
    },
    handleSteram(stream) {
      let tempTable = stream[0].text
        .replace("[", "")
        .replace("]", "")
        .split("\n");
      let tempHeader = [];
      let temp = [];
      tempTable.forEach((ele, i) => {
        if (i == 0) {
          tempHeader = ["index", ...ele.trim().split("  ")].filter(
            (item) => item.length
          );
        } else {
          let transitional = ele.trim().split(" ");
          temp.push(transitional.filter((e) => e));
        }
      });
      let table = [];
      temp.forEach((e) => {
        let t = {};
        e.forEach((ele, i) => {
          if (tempHeader[i]) {
            t[tempHeader[i]] = ele;
          }
        });
        table.push(t);
      });

      this.resultData = {
        table: table,
        tableHead: tempHeader,
      };
      this.showBottomResult = true;
      console.log(table);
    },
    // 初始化开始节点
    initGraphStart() {
      graph.clearCells();
      graph.center(); // 内容居中
      graph.zoomTo(1); // 缩放比例
      // const start_node = graph.createNode({
      //   shape: "start",
      //   x: 100,
      //   y: 300
      // });
      // graph.addNode(start_node);
    },
    // 初始化点击事件
    async initClickEvent() {
      graph.on("blank:click", async () => {
        if (this.currentCell !== null) {
          this.clearData();
        }
      });
      graph.on("cell:click", ({ cell }) => {
        let isNode = cell.isNode();
        this.clearData();
        if (isNode) {
          this.getNodeInfo(cell);
        }
      });
    },

    // 获取被选中节点的数据
    getNodeInfo(cell) {
      console.log(cell);
      this.currentSelect = cell.shape;
      this.currentCell = cell;
      console.log(this.dagStructure);
      console.log(cell.id);
      if (this.dagStructure[cell.id]) {
        this.handleRes(this.dagStructure[cell.id].result);
      }
      console.log(cell);
      this.cellData = cell.getData();
      console.log(this.cellData);
      let nodeAttrs = cell.getAttrs();
      this.cellData.name = nodeAttrs?.label?.text;
    },
    // 清空选中节点数据
    clearData() {
      let data = this.$options.data();
      // console.log(data)
      // console.log(data.config)
      // this.cellData = data.config;
      this.currentCell = null;
      this.currentSelect = "none";
      this.cellData = data.cellData;
      this.showBottomResult = false;
    },
    // 设置当前选中节点的数据
    setNodeInfo(val) {
      console.log("主页---------->val", val);
      this.cellData = val;
      if (val?.name) {
        let attr = {
          label: {
            text: this.cellData.name,
          },
        };
        this.currentCell.setAttrs(attr);
      }
      let options = {
        silent: true,
        overwrite: true,
      };
      this.currentCell.setData(this.cellData, options);
    },
    // 保存dag图数据
    async handleSaveDag() {
      let allData = graph.toJSON();
      let [thisData] = allData.cells.filter((e) => e.shape != "edge");
      console.log(thisData);
      let canvas_id = this.$route.query.canvas_id;
      console.log(
        { allData, thisData, canvas_id },
        "{ allData, thisData, canvas_id }"
      );
      await this.saveCanvas({ allData, thisData, canvas_id });

      await this.initDagGraph();

      // let lastData = {}
      // lastData.cells = JSON.stringify(graphData.cells)
      // lastData.data = []

      // let tempGraphData = graphData.cells.filter(e => e.shape != 'edge')
      // tempGraphData.forEach(e => {
      //   let temp = {}
      //   temp.id = e.myId
      //   temp.moduleId = e.id
      //   temp.params = []
      //   temp.in = []
      //   temp.out = []
      //   let tempIn = e.ports.items.filter(e => e.group == 'in')
      //   let tempOut = e.ports.items.filter(e => e.group == 'out')
      //   tempIn.forEach(ele => {
      //     let t = {}
      //     t.id = ele.id
      //     t.toId = ele.moduleId
      //     t.targetPort = ele.myId
      //     temp.in.push(t)
      //   })
      //   tempOut.forEach(ele => {
      //     let t = {}
      //     t.id = ele.id
      //     t.toId = ele.moduleId
      //     t.targetPort = ele.myId
      //     temp.out.push(t)
      //   })
      //   lastData.data.push(temp)
      // })
      // console.log(lastData)
      // // console.log(JSON.stringify(graph.toJSON()))
      // // let graphData = graph.toJSON()
      // this.graphData = graph.toJSON();
    },
    backPage() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="less">
@import "./index.less";

.dag-box {
  height: 100%;
}

.go-back {
  background: url(~@/assets/img/go-back.png) center center no-repeat;
  display: block;
  width: 56px;
  height: 44px;
  background-size: 16px 16px;
}

.dag-nav {
  position: absolute;
  left: 0;
  top: 0;
  width: 56px;
  border-top: solid 1px #e6e6e6;
  border-right: solid 1px #e6e6e6;
  // background-color: #FFF;
  height: 100%;
  box-sizing: border-box;

  // padding-top: 64px;
  li {
    line-height: 56px;
    text-align: center;
    cursor: pointer;
  }

  .active {
    background: #1e2480;
    color: #fff;
  }
}

.bottom-result-img {
  display: block;
  margin: 20px auto 0;
  max-height: 95%;
}

// //临时全为白色
// .dag-nav li {
//   color: #000000;
// }

// .task-name {
//   color: #000000 !important;
// }

.file-lis .name {
  color: #000;
}

.right-content {
  .el-button {
    padding: 10px 10px;
    font-size: 14px !important;
    border-radius: 4px;
    color: #fff;
    border: 0;
  }
}

.list-box {
  .self-menu {
    background: transparent;
    border-right: 0;
  }
}

.wrap .panel-left {
  background: #f2f6fc;
  z-index: 99;
  // background: #1A1E2C;
}
</style>
